'use strict';

(function () {
	var canvas = document.getElementById('canvas'),
	    ctx = canvas.getContext('2d'),
	    nodeColor = '#fff',
	    backgroundColor = '#000',
	    nodes = [];

	function constructStars() {
		var i = void 0;
		for (i = 0; i < 100; i++) {
			var r = Math.random();
			var node = {
				x: Math.random() * canvas.width,
				y: Math.random() * canvas.height,
				vx: Math.random() * 1 - 0.5,
				vy: Math.random() * 1 - 0.5,
				radius: r < 0.1 ? r * 3 + 1 : r * 3
			};
			nodes.push(node);
		}
		render();
	}

	function step() {
		nodes.forEach(function (node) {
			node.x += node.vx;
			node.y += node.vy;

			function scope(min, max, value) {
				if (value < min) {
					return min;
				} else if (value > max) {
					return max;
				} else {
					return value;
				}
			}

			if (node.x <= 0 || node.x >= canvas.width) {
				node.vx *= -1;
				node.x = scope(0, canvas.width, node.x);
			}

			if (node.y <= 0 || node.y >= canvas.height) {
				node.vy *= -1;
				node.y = scope(0, canvas.height, node.y);
			}
		});

		render();
		window.requestAnimationFrame(step);
	}

	function render() {
		ctx.fillStyle = backgroundColor;
		ctx.fillRect(0, 0, canvas.width, canvas.height);
		nodes.forEach(function (node) {
			ctx.fillStyle = nodeColor;
			ctx.beginPath();
			ctx.arc(node.x, node.y, node.radius, 0, 2 * Math.PI);
			ctx.fill();
		});
	}

	window.onresize = function () {
		canvas.width = document.body.clientWidth;
		canvas.height = canvas.height;
		if (nodes.length === 0) {
			constructStars();
		}
		render();
	};
	window.onresize();
	window.requestAnimationFrame(step);
}).call(undefined);
